import json
import itertools
from cou.utils.catchdata import catchdata
import copy
from pprint import pprint

def tanxin(upper,foods_price):
    foodprice_list=[]
    total_price=0
    finish_flag=False
    while not finish_flag:
        price_cha=[]
        for food_price in foods_price:
            price_cha.append(abs(upper-total_price-food_price))
        next_foodprice_index=price_cha.index(min(price_cha))#返回形成最小差值食物价格的下标
        foodprice_list.append(foods_price[next_foodprice_index])#将此食物价格加入列表
        total_price+=foodprice_list[-1]
        if(total_price>=upper):
            finish_flag=True
    return foodprice_list

def youhua_manjian(bestlist,foods_price,upper,minimum_order_amount,essentialfood):#在得到第一个满减序列之后演化出后面的满减队列
    foodsprice_index=0
    while(max(bestlist[foodsprice_index])>=15 and max(bestlist[foodsprice_index])!=essentialfood):
       bestfirst_price=sum(bestlist[foodsprice_index])#前一位列表的和
       bestlist.append(copy.deepcopy(bestlist[foodsprice_index]))
       maxfoodprice_index=bestlist[foodsprice_index].index(max(bestlist[foodsprice_index]))
    
       foods_seprice=[]
       for food in foods_price:
           if(food<max(bestlist[foodsprice_index])):
               foods_seprice.append(food)
       if foods_seprice:
           for i in tanxin(max(bestlist[foodsprice_index])-(bestfirst_price-upper),foods_seprice):
               bestlist[foodsprice_index+1].append(i)
           bestlist[foodsprice_index+1].pop(maxfoodprice_index)#将最大位取出，新的一个数列形成
           foodsprice_index+=1
    
       else:
           break;#商品中已经没有比15小的商品了
       if(len(bestlist[foodsprice_index])>40):#商品过多
           bestlist.pop()
           foodsprice_index=foodsprice_index-1
           break
       if(len(bestlist)>=20):
           break#数目过多，跳出
    
       #--------------------防止单个价格的食品个数不会过多---------------------------
       for food in bestlist[foodsprice_index]:
           if(bestlist[foodsprice_index].count(food)>=4  and food<=4):#单个价格食物大于等于4，且单价小于等于4
               food_number=bestlist[foodsprice_index].count(food)
               foods_seprice=[]
               for food_price in foods_price:
                   if(food_price<=bestlist[foodsprice_index].count(food)*food):
                       foods_seprice.append(food_price)
               if foods_seprice:
                   for i in tanxin(food_number*food,foods_seprice):
                       bestlist[foodsprice_index].append(i)
                       if(len(bestlist[foodsprice_index])>40):
                           break
                   for i in range(food_number):
                       bestlist[foodsprice_index].remove(food)
       if(len(bestlist[foodsprice_index])>40):
            bestlist.pop()
            foodsprice_index=foodsprice_index-1
            break
    if(bestlist):
        for foodindex1 in bestlist:#将相同的情况删除
            for foodindex2 in (bestlist[bestlist.index(foodindex1)+1::]):
                if(foodindex1==foodindex2):
                    bestlist.pop(bestlist.index(foodindex2))
        cancel_index=True
        while cancel_index:
            cancel_index=False
            for foodlist in bestlist:#将价格低于起送价的队列删除
                if(sum(foodlist)<minimum_order_amount):
                    bestlist.pop(bestlist.index(foodlist))
                    continue
                    cancel_index=True
                if(len(foodlist)>=15):#将商品过多的情况过滤
                    bestlist.pop(bestlist.index(foodlist))
                    cancel_index=True

def check_single(name):
    filters_name=["单点","单拍","不单装","收臧","不配送","不送","不点主"]
    for i in filters_name:
        if i in name:
            return True
    return False
def data_integration(bestlist,merchant,upper,devalue,shop_img_url,foods,fin_data,rating):#数据封装
    #pprint(bestlist)
    for flist in bestlist:
        one_tactic=dict()
        one_tactic["name"]=merchant
        one_tactic["rating"]=rating
        one_tactic["man"]=upper
        one_tactic["jian"]=devalue
        one_tactic["totalcost"]=round(sum(flist),3)#食物原价
        # if(one_tactic["totalcost"]>one_tactic["man"]+one_tactic["jian"]):
        #     continue
        one_tactic["shopImgUrl"]=shop_img_url
        #装填食物信息
        one_tactic["food"]=[]
        
        fset=list(set(flist))
        for foodprice in fset:
            for food_inf in foods:
                if(food_inf["food_price"]==foodprice):
                    f_dict={}
                    f_dict["food_name"]=food_inf["food_name"]
                    f_dict["food_price"]=food_inf["food_price"]
                    f_dict["food_img_url"]=food_inf["food_img_url"]
                    f_dict["num"]=flist.count(foodprice)
                    one_tactic["food"].append(f_dict)
                    break#已经找到一个商品
        dandian_index=0
        for tactic_foods in range(len(one_tactic["food"])):#用于保证餐点中无只有单点不送的食品
            tactic_foods_name = one_tactic["food"][tactic_foods]["food_name"]
            tactic_foods_price = one_tactic["food"][tactic_foods]["food_price"]
            if (check_single(tactic_foods_name) or tactic_foods_price<=2):
                dandian_index += 1
        if (dandian_index == len(one_tactic["food"])):
            break
        yield(one_tactic)
        
        

def handle_data(value,merchant):#处理数据
    for i in range(len(value)):
    #for i in range(117,119):#先做前几家试试看
        reduction=value[i]["reduction"]#满减信息字典，其中key为满减下限，值为减值
        foods=value[i]["foods"]#食物列表其中包括{"food_name"：值，"food_price"：值，"food_img_url":值}
        essential_food=value[i]["essential_food"]#必点食物列表
        shop_img_url=value[i]["shop_img_url"]#商铺图片url
        red_upper=[float(i) for i in reduction.keys()]#满减上限
        red_devalue=list(reduction.values())#满减减值
        minimum_order_amount=value[i]["minimum_order_amount"]#最低配送价格
        rating=value[i]["rating"]#商家评分
        foods_name=[]#一个商家中所有商品名称，元素为字符串
        foods_price=[]#一个商家中所有商品价格,元素为浮点数
        foods_img_url=[]#一个商家中所有商品的图片url
        essentialfoods_name=[]#所有必点商品的名称
        essentialfoods_price=[]#所有必点商品的价格
    
    
        for j in range(len(foods)):
            foods_name.append(foods[j]["food_name"])
            foods_price.append(foods[j]["food_price"])
            foods_img_url.append(foods[j]["food_img_url"])
        for j in range(len(essential_food)):
            essentialfoods_name.append(essential_food[j]["food_name"])
            essentialfoods_price.append(essential_food[j]["food_price"])
        #pprint(merchant[i])
        foods_price=list(set(foods_price))#将重复的商品价格去除
        essentialfoods_price=list(set(essentialfoods_price))
        #print(red_upper,foods_price,essentialfoods_price)

        if(essentialfoods_price):#如果有必选品,将必选品从正常食物中取出
                for essentialfood in essentialfoods_price:
                    foods_price.pop(foods_price.index(essentialfood))

        for j in range(len(red_upper)):#以每个商家的每个满减数值形成多个满减队列
            upper=red_upper[j]
            devalue=red_devalue[j]#满减上限
        
            bestlist=[]#用于存放各种价格最适合的食物价格列表
            if(foods_price):#如果这家点没有原价食品（无法进行满减）则直接跳出
                if(essentialfoods_price):#如果有必选品
                    for essentialfood in essentialfoods_price:
                        bestlist=[]
                        bestlist.append(tanxin(upper-essentialfood,foods_price))#完成第一次满减
                        bestlist[0].append(essentialfood)
                        youhua_manjian(bestlist,foods_price,upper,minimum_order_amount,essentialfood)
                        fin_data=[]
                        for a in data_integration(bestlist,merchant[i],upper,devalue,shop_img_url,foods,fin_data,rating):
                            yield(a)
                        
                        #pprint(one_tactic)
                else:#无必选品
                    bestlist.append(tanxin(upper,foods_price))#完成第一次满减
                    youhua_manjian(bestlist,foods_price,upper,minimum_order_amount,0)
                    fin_data=[]
                    for b in data_integration(bestlist,merchant[i],upper,devalue,shop_img_url,foods,fin_data,rating):
                            yield(b)
            else:
                break
    
if __name__ == "__main__":
    
    #filename="E:\\full_reduction\\data2.4.json"
    filename="data2.4.json"
    f_obj=open(filename,encoding = 'utf-8')
    data=json.load(f_obj)
    a=catchdata()
    value,merchant=a.full_reductiondata(data)
    #fin_data=handle_data(value,merchant)
    for i in handle_data(value,merchant):
        pprint(i)
    #pprint(fin_data)

    #with open("record.json","w",encoding="utf-8") as f:
    #     json.dump(fin_data,f,ensure_ascii=False,indent=2)
    #     print("加载入文件完成...")
    f_obj.close()
